package com.wenx.server;

import com.wenx.InvokeMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.Map;

/**
 * 不返回数据
 */
public class RpcServerHandler extends SimpleChannelInboundHandler<InvokeMessage> {

    private Map<String,Object>  registerMap;

    public RpcServerHandler(Map<String, Object> registerMap) {
        this.registerMap = registerMap;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, InvokeMessage invokeMessage) throws Exception {
        Object result = "没有可用的服务提供者";
        // 判断注册中心中是否有指定名称的服务
        if(registerMap.containsKey(invokeMessage.getClassName())) {
            Object provider = registerMap.get(invokeMessage.getClassName());
            //反射执行方法
            result = provider.getClass()
                    .getMethod(invokeMessage.getMethodName(), invokeMessage.getParamTypes())
                    .invoke(provider, invokeMessage.getParamValues());
        }
        //将该运算结果发送给客户端
        channelHandlerContext.writeAndFlush(result);
        channelHandlerContext.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //super.exceptionCaught(ctx, cause);
        //打印异常
        cause.printStackTrace();
        ctx.close();
    }
}
